package com.itheima.reggie.commons;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.PrintWriter;

@Slf4j
public class CheckLoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1. 从会话域中获取用户信息
        HttpSession session = request.getSession();
        Long loginId = (Long) session.getAttribute("LOGIN_ID");
        //2. 如果不为空则放行，返回true
        if (loginId != null) {
            log.info("已登录用户:{}放行", loginId);
            return true;
        }
        //3. 为空，则使用打印流输出R.error("NOTLOGIN")错误信息到客户端，并且返回false
        else {
            log.info("拦截到非法访问地址：{}", request.getRequestURI());
            response.setContentType("application/json;charset=utf-8");
            PrintWriter out = response.getWriter();
            //转成JSON字符串打印回去
            String json = JSON.toJSONString(R.error("NOTLOGIN"));
            out.print(json);
            //返回false拦截
            return false;
        }
    }
}
